package mju.cxf.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import mju.cxf.dto.ProductSpecificationsDTO;
import mju.cxf.entity.Categories;
import mju.cxf.entity.Product;
import mju.cxf.entity.ProductSpecifications;
import mju.cxf.mapper.ProductSpecificationsMapper;
import mju.cxf.service.ProductSpecificationsService;
import mju.cxf.utils.TimestampUpdaterUtils;
import mju.cxf.vo.ProductSpecificationsListVO;
import mju.cxf.vo.ProductSpecificationsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 商品规格服务类
 *
 * @author lechangxin, wangx, zhengx
 * @version 1.0
 * @see ProductSpecificationsService
 */
@Service
class ProductSpecificationsServiceImpl extends ServiceImpl<ProductSpecificationsMapper, ProductSpecifications> implements ProductSpecificationsService {
    @Autowired
    private ProductServiceImpl productServiceImpl;
    @Autowired
    private PhotoServiceImpl photoServiceImpl;
    /**
     * A分页查询商品规格信息
     *
     * @return boolean
     */
    @Override
    public Page<ProductSpecificationsVO> selectPage(String name, Integer state, Integer minPrice, Integer maxPrice, Integer minNumber, Integer maxNumber, int current, int size) {
        Page<ProductSpecificationsVO> page = new Page<>(current, size);
        return this.baseMapper.selectPageVo(page, name, state, minPrice, maxPrice, minNumber, maxNumber);
    }


    /**
     * A修改商品规格息
     *
     * @return list
     * @author wx
     * @since 2024-10-18
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProduct(ProductSpecificationsDTO productSpecificationsDTO) {
        ProductSpecifications productSpecifications = new ProductSpecifications();
        productSpecificationsDTO.setUpdateTime(LocalDateTime.now());
        BeanUtils.copyProperties(productSpecificationsDTO, productSpecifications);
        productSpecifications.setImageUrl(JSON.toJSONString(productSpecificationsDTO.getImageUrls()));
        ProductSpecifications ps = this.getById(productSpecificationsDTO.getId());
        //插入修改时间和修改人
        TimestampUpdaterUtils.updateUtil(productSpecifications);
        LambdaUpdateWrapper<ProductSpecifications> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper
                .eq(ProductSpecifications::getId, productSpecifications.getId())
                .set(ProductSpecifications::getImageUrl, productSpecifications.getImageUrl());
        if (this.update(productSpecifications, updateWrapper)) {
            if (!(Objects.equals(ps.getImageUrl(), productSpecifications.getImageUrl()))) {
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    List<String> itemList = objectMapper.readValue(ps.getImageUrl(), new TypeReference<List<String>>() {
                    });
                    itemList.forEach(item -> {
                        photoServiceImpl.addRedis(item);
                    });
                    productSpecificationsDTO.getImageUrls().forEach(image -> {
                        photoServiceImpl.saveImages(image);
                    });
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }

            }
            productSpecifications.setUpdateTime(LocalDateTime.now());
            return true;
        }
        return false;
    }

    /**
     * A删除规格信息
     *
     * @param id 需要修改的规格信息id
     * @return boolean 是否删除成功
     */
    @Override
    public boolean deleteProduct(Integer id) {
        ProductSpecifications byId = this.getById(id);

        if (this.removeById(id)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<String> itemList = objectMapper.readValue(byId.getImageUrl(), new TypeReference<List<String>>() {
                });
                itemList.forEach(item -> {
                    photoServiceImpl.deleteUrl(item);
                });
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
        return false;
    }

    /**
     * A查询商品信息
     * @return
     */
    @Override
    public ProductSpecifications selectSpecifications(int id){
        return this.baseMapper.selectById(id);
    }

    /**
     * A新增商品规格
     *
     * @param productSpecificationsDTO 需要新增的规格信息
     * @return boolean 是否新增成功
     */
    @Override
    public boolean saveProductSpecifications(ProductSpecificationsDTO productSpecificationsDTO) {
        ProductSpecifications productSpecifications = new ProductSpecifications();
//        productSpecificationsDTO.setState(1);
        productSpecificationsDTO.setCreateTime(LocalDateTime.now());
        Product product = productServiceImpl.selectProduct(productSpecificationsDTO.getProductId());
        productSpecifications.setProductId(product.getId());
        productSpecifications.setIconUrl(product.getImageUrl());
        productSpecifications.setImageUrl(JSON.toJSONString(productSpecificationsDTO.getImageUrls()));
        BeanUtils.copyProperties(productSpecificationsDTO, productSpecifications);
        TimestampUpdaterUtils.saveUtil(productSpecifications);
        boolean save = this.save(productSpecifications);
        if (save) {
            productSpecificationsDTO.getImageUrls().forEach(photoServiceImpl::saveImages);
            return true;
        }
        return false;
    }

    /**
     * U展示一个商品详细信息
     *
     * @param id 商品规格Id
     * @return productSpecifications 商品数据
     */
    public ProductSpecifications uSelectProductSpecificationsById(Integer id) {
        ProductSpecifications productSpecifications = this.baseMapper.selectById(id);
        productSpecifications.setClicks(productSpecifications.getClicks() + 1);
        this.baseMapper.updateById(productSpecifications);
        return productSpecifications;
    }

    /**
     * U用户分页展示商品规格
     *
     * @param id      当前需要获取规格的商品Id
     * @param current 当前页
     * @param size    页面大小
     * @return 各类商品规格
     */
    @Override
    public ProductSpecificationsListVO userPageBySpecifications(int id, int current, int size) {
        Page<ProductSpecifications> page = new Page<>(current, size);
        LambdaQueryWrapper<ProductSpecifications> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ProductSpecifications::getProductId, id);
        lqw.eq(ProductSpecifications::getState, 0);
        lqw.orderByDesc(ProductSpecifications::getClicks);
        Page<ProductSpecifications> productSpecificationsPage = baseMapper.selectPage(page, lqw);
        int m = (int) (productSpecificationsPage.getTotal() % productSpecificationsPage.getSize());
        int numsPerPage = (int) (productSpecificationsPage.getTotal() / productSpecificationsPage.getSize());
        return ProductSpecificationsListVO.builder()
                .count((int) productSpecificationsPage.getTotal())
                .currentPage((int) productSpecificationsPage.getCurrent())
                .filterCategory(null)
                .totalPages(m > 0 ? numsPerPage + 1 : numsPerPage)
                .goodsList(productSpecificationsPage.getRecords())
                .numsPerPage((int) productSpecificationsPage.getSize())
                .data(null)
                .build();
    }
}
